package router

import (
	"fmt"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	"github.com/zh-five/xdaemon"
	"go.uber.org/zap"
	"kf/middleware"
	"kf/models/dao"
	"kf/tools"
	"kf/ws"
	"log"
	"os"
)

type Server struct {
	Api          *Api
	LoggerSave   *middleware.LoggerSave
	MidLogger    *middleware.MidLogger
	Err          *middleware.Err
	WsLogic      *ws.WsLogic
	ConfigDao    *dao.ConfigDao
	SysAutoReply *dao.SysAutoReplyDao
	Ws           *ws.WsVisitor
	Log          *zap.Logger
}

var (
	Port        string
	Daemon      bool
	enableDebug bool
)

func (server *Server) Run() {
	if Daemon == true {
		logFilePath := ""
		if dir, err := os.Getwd(); err == nil {
			logFilePath = dir + "/logs/"
		}
		_, err := os.Stat(logFilePath)
		if os.IsNotExist(err) {
			if err := os.MkdirAll(logFilePath, 0777); err != nil {
				log.Println(err.Error())
			}
		}
		// 初始化配置文件
		//config.InitAppConfig(*configFile)
		d := xdaemon.NewDaemon(logFilePath + "go-fly.log")
		d.MaxCount = 10
		d.Run()
	}

	baseServer := "0.0.0.0:" + Port
	server.Log.Info("start Server...\ngo：http://", zap.String("server", baseServer))
	engine := gin.Default()
	//if common.IsCompireTemplate {
	//	templ := template.Must(template.New("").ParseFS(static.TemplatesEmbed, "templates/*.html"))
	//	engine.SetHTMLTemplate(templ)
	//	engine.StaticFS("/assets", http.FS(static.JsEmbed))
	//} else {
	engine.LoadHTMLGlob("static/templates/*")
	engine.Static("/assets", "./static")
	//}
	engine.Static("/static", "./static")
	engine.Use(middleware.CrossSite)
	engine.Use(server.Err.Recovery())
	//性能监控
	pprof.Register(engine, "dev/pprof")
	InitViewRouter(engine)
	server.Api.InitApiRouter(engine)
	//记录日志
	engine.Use(server.MidLogger.NewMidLogger())

	//记录pid
	os.WriteFile("kefu.sock", []byte(fmt.Sprintf("%d,%d", os.Getppid(), os.Getpid())), 0666)
	//限流类
	tools.NewLimitQueue()
	//清理
	server.Ws.CleanVisitorExpire()
	//后端websocket
	go server.WsLogic.WsServerBackend()
	//ws初始化
	server.WsLogic.Init()
	//初始化config
	server.ConfigDao.InitConfig()
	//初始化自动回复
	server.SysAutoReply.InitSysAutoReply()
	// 启动日志worker
	go server.LoggerSave.LogWorker()

	err := engine.Run(baseServer)
	if err != nil {
		return
	}
}
